package com.ruoyi.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import com.ruoyi.system.service.ISysUserRoleService;
import org.springframework.stereotype.Service;

import java.util.List;

/***
 *@title SysUserRoleServiceImpl
 *@description 用户与角色关联表 业务层处理
 *@author 陈九常
 *@version 1.0.0
 *@create 2025/10/30 23:45
 **/
@Service
public class SysUserRoleServiceImpl extends ServiceImpl<SysUserRoleMapper, SysUserRole> implements ISysUserRoleService {

    /**
     * 通过用户ID删除用户和角色关联
     *
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    public int deleteUserRoleByUserId(Long userId) {
        LambdaUpdateWrapper<SysUserRole> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(SysUserRole::getUserId, userId);
        return baseMapper.delete(wrapper);
    }

    /**
     * 批量删除用户和角色关联
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteUserRole(Long[] ids) {
        LambdaUpdateWrapper<SysUserRole> wrapper = new LambdaUpdateWrapper<>();
        wrapper.in(SysUserRole::getUserId, (Object[]) ids);
        return baseMapper.delete(wrapper);
    }

    /**
     * 通过角色ID查询角色使用数量
     *
     * @param roleId 角色ID
     * @return 结果
     */
    @Override
    public int countUserRoleByRoleId(Long roleId) {
        LambdaQueryWrapper<SysUserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUserRole::getRoleId, roleId);
        return Math.toIntExact(baseMapper.selectCount(wrapper));
    }

    /**
     * 批量新增用户角色信息
     *
     * @param userRoleList 用户角色列表
     * @return 结果
     */
    @Override
    public int batchUserRole(List<SysUserRole> userRoleList) {
        return userRoleList.stream()
                .mapToInt(userRole -> baseMapper.insert(userRole))
                .sum();
    }

    /**
     * 删除用户和角色关联信息
     *
     * @param userRole 用户和角色关联信息
     * @return 结果
     */
    @Override
    public int deleteUserRoleInfo(SysUserRole userRole) {
        LambdaUpdateWrapper<SysUserRole> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(SysUserRole::getUserId, userRole.getUserId())
                .eq(SysUserRole::getRoleId, userRole.getRoleId());
        return baseMapper.delete(wrapper);
    }

    /**
     * 批量取消授权用户角色
     *
     * @param roleId  角色ID
     * @param userIds 需要删除的用户数据ID
     * @return 结果
     */
    @Override
    public int deleteUserRoleInfos(Long roleId, Long[] userIds) {
        LambdaUpdateWrapper<SysUserRole> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(SysUserRole::getRoleId, roleId)
                .in(SysUserRole::getUserId, (Object[]) userIds);
        return baseMapper.delete(wrapper);
    }
}
